<?php
class GoodsController extends AppController {

	public $name = 'goods';
	function beforeFilter() {
	    parent::beforeFilter(); 
		//$this->C_auth->autoRedirect = false; //For override login
	   // $this->C_auth->allowedActions = array('index','add','edit','ulist','del','swfupload','swfdelimage','gallerydrop','galleryset','categorylist','categoryadd','categoryedit','categorydel','gallery','getcatlist','getcatbrandlist','getattributelist','getshopimgselect','getucategoryadd');

	}	

	public function categorylist() {
	    $this->_teamRights();
		$query = array(
				'fields' => array('shopusercategorie.*'),
				'conditions' => array('shopusercategorie.shop_id' => $this->my->id),
				'order' => 'sort_order asc'
				);	
        $category_list = POP::exe('[@@:UM shopusercategorie][@@:QU find:all]',$query);	

        $category_list_new = array();
        if(!empty($category_list)) {
	        foreach($category_list as $v) {
		        $category_list_new[$v['shopusercategorie']['id']]['id'] = $v['shopusercategorie']['id'];
		        $category_list_new[$v['shopusercategorie']['id']]['shop_cat_name'] = $v['shopusercategorie']['shop_cat_name'];
		        $category_list_new[$v['shopusercategorie']['id']]['parent_id'] = $v['shopusercategorie']['parent_id'];
		        $category_list_new[$v['shopusercategorie']['id']]['shop_cat_unit'] = $v['shopusercategorie']['shop_cat_unit'];
		        $category_list_new[$v['shopusercategorie']['id']]['sort_order'] = $v['shopusercategorie']['sort_order'];
	        }
        }
        unset($category_list);
        $this->set('category_list_new',$category_list_new);	
	}
	
	public function categoryadd($id=0) {
        $this->_teamRights();	
		if (!empty($this->data)) {	
			$query = array(
					'fields' => array('shopusercategorie.*'),
					'conditions' => array('AND' => array('shopusercategorie.shop_cat_name' => $this->data['shopusercategorie']['shop_cat_name'],'shopusercategorie.shop_id' => $this->my->id, 'shopusercategorie.parent_id' => 0))),
					);	
			$tempshopinfo = POP::exe('[@@:UM shopusercategorie][@@:QU find:first]',$query);	
			
			if(!empty($tempshopinfo)) {
			    $this->flash('该分类名已经存在!', Router::url('goods/categoryadd/'.$id));
            }else{						
				$safeData = $this->data;
				if ( POP::exe('[@@:UM shopusercategorie][@@:QU save]',$safeData)) {
					$this->flash('更新成功！', Router::url('goods/categorylist'));		
				} else {
					$this->flash('更新失败！', Router::url('goods/categorylist'));
				}				
            }			
	    }	
        $shop_category_info = array(
	        'shop_cat_name'	=> '',
	        'parent_id'		=> intval($id),
	        'shop_cat_unit'	=> '',
	        'sort_order'	=> 0
        );		
		
		$query = array(
				'fields' => array('shopusercategorie.*'),
				'conditions' => array('shopusercategorie.shop_id' => $this->my->id),
				'order' => 'sort_order asc'
				);	
        $category_list = POP::exe('[@@:UM shopusercategorie][@@:QU find:all]',$query);	

        $category_list_new = array();
        if(!empty($category_list)) {
	        foreach($category_list as $v) {
		        $category_list_new[$v['shopusercategorie']['id']]['id'] = $v['shopusercategorie']['id'];
		        $category_list_new[$v['shopusercategorie']['id']]['shop_cat_name'] = $v['shopusercategorie']['shop_cat_name'];
		        $category_list_new[$v['shopusercategorie']['id']]['parent_id'] = $v['shopusercategorie']['parent_id'];
		        $category_list_new[$v['shopusercategorie']['id']]['shop_cat_unit'] = $v['shopusercategorie']['shop_cat_unit'];
		        $category_list_new[$v['shopusercategorie']['id']]['sort_order'] = $v['shopusercategorie']['sort_order'];
	        }
        }
        unset($category_list);
        $this->set('category_list_new',$category_list_new);		
        $this->set('shop_id',$this->my->id);
        $this->set('shop_category_info',$shop_category_info);		
	}	
	
	public function categoryedit($id=0) {
        $this->_teamRights();	
		if (!empty($this->data)) {
			$query = array(
					'fields' => array('shopusercategorie.*'),
					'conditions' => array('AND' => array('shopusercategorie.shop_cat_name' => $this->data['shopusercategorie']['shop_cat_name'],'shopusercategorie.shop_id' => $this->my->id, 'shopusercategorie.parent_id' => 0, 'shopusercategorie.id<>' => $id))),
					);	
			$tempshopinfo = POP::exe('[@@:UM shopusercategorie][@@:QU find:first]',$query);				

			$query = array(
					'fields' => array('shopusercategorie.*'),
					'conditions' => array('AND' => array('shopusercategorie.id' => $id,'shopusercategorie.shop_id' => $this->my->id))),
					);	
			$tempshopinfo1 = POP::exe('[@@:UM shopusercategorie][@@:QU find:first]',$query);			

			$query = array(
					'fields' => array('shopusercategorie.*'),
					'conditions' => array('AND' => array('shopusercategorie.id' => $this->data['shopusercategorie']['parent_id'],'shopusercategorie.shop_id' => $this->my->id, 'shopusercategorie.parent_id' => 0)),
					);	
			$tempshopinfo2 = POP::exe('[@@:UM shopusercategorie][@@:QU find:first]',$query);			
	
			$tempshopinfo3 = 0;
			if(isset($tempshopinfo2['shopusercategorie']['id'])) {
				$query = array(
						'fields' => array('shopusercategorie.*'),
						'conditions' => array('AND' => array('shopusercategorie.parent_id' => $tempshopinfo2['shopusercategorie']['id'],'shopusercategorie.shop_id' => $this->my->id)),
						);	
				$tempshopinfo3 = POP::exe('[@@:UM shopusercategorie][@@:QU find:first]',$query);			
			}
            if($tempshopinfo1['shopusercategorie']['parent_id']==0 && isset($tempshopinfo2['shopusercategorie']['id']) && isset($tempshopinfo3['shopusercategorie']['id'])){
			    $this->flash('该上级分类还有下级分类！', Router::url('goods/categoryedit/'.$id));
			}else {
				if($id == $this->data['shopusercategorie']['parent_id']) {
					$this->flash('不能把自己设置自己的上级分类！', Router::url('goods/categoryedit/'.$id));
				}else {			
					if(!empty($tempshopinfo)) {
					$this->flash('该分类名已经存在!', Router::url('goods/categoryedit/'.$id));
					}else{									
						$safeData = $this->data;
						$query  = array();		
						$query['keyid'] = $id;				
						$query['set'] = $safeData;					
						if (POP::exe('[@@:UM shopusercategorie][@@:QU save]',$safeData)) {
							$this->flash('更新成功！', Router::url('goods/categorylist'));		
						} else {
							$this->flash('更新失败！', Router::url('goods/categorylist'));
						}				
					
					}
				}
            } 			
	    }		

 		$query = array(
				'fields' => array('shopusercategorie.*'),
				'conditions' => array('shopusercategorie.shop_id' => $this->my->id),
				'order' => 'sort_order asc'
				);	
        $category_list = POP::exe('[@@:UM shopusercategorie][@@:QU find:all]',$query);	

        $category_list_new = array();
        if(!empty($category_list)) {
	        foreach($category_list as $v) {
		        $category_list_new[$v['shopusercategorie']['id']]['id'] = $v['shopusercategorie']['id'];
		        $category_list_new[$v['shopusercategorie']['id']]['shop_cat_name'] = $v['shopusercategorie']['shop_cat_name'];
		        $category_list_new[$v['shopusercategorie']['id']]['parent_id'] = $v['shopusercategorie']['parent_id'];
		        $category_list_new[$v['shopusercategorie']['id']]['shop_cat_unit'] = $v['shopusercategorie']['shop_cat_unit'];
		        $category_list_new[$v['shopusercategorie']['id']]['sort_order'] = $v['shopusercategorie']['sort_order'];
	        }
        }
        unset($category_list);
        $shop_category_info = $category_list_new[$id];	
        $this->set('category_list_new',$category_list_new);		
        $this->set('shop_id',$this->my->id);
        $this->set('shop_category_info',$shop_category_info);		
	}	
	
	
	public function categorydel($id) {
        $this->_teamRights();	
		$query = array(
				'fields' => array('shopusercategorie.*'),
				'conditions' => array('shopusercategorie.parent_id' => $id),
				);	
		$parent_id_last = POP::exe('[@@:UM shopusercategorie][@@:QU find:first]',$query);	

		$query = array(
				'fields' => array('goods.*'),
				'conditions' => array('goods.ucat_id' => $id),
				);	
		$goods_id_last = POP::exe('[@@:UM goods][@@:QU find:first]',$query);
	
        if(isset($parent_id_last['shopusercategorie']['id'])) {
		    $this->flash('删除失败，请先删除该项的子项目！', Router::url('goods/categorylist'));			 
		}else if ($goods_id_last['goods']['ucat_id']>0) {
		    $this->flash('删除失败，请先删除该分类的产品内容！', Router::url('goods/categorylist'));
		}else {
			$query = array('keyid'=>$id);			
			POP::exe('[@@:UM shopusercategorie][@@:QU del]',$query);			
		    $this->flash('删除成功！', Router::url('goods/categorylist'));
        }
	}
	
	
	
	
	public function index() {
	

/*     print_r($this->post); */

/* 		    print_r($this->C_session->returnSessionVars());	
 	   echo  $this->C_session->read('Controller.sessKey');	 */		
 	    $this->C_session->delete('Controller.sessKey');		
	/* 	print_r($_SESSION);print_r($this->C_session->id());  */
	$this->set('i','nihao');
	}	

	public function ulist() {
        $this->_teamRights();	
        $page = intval(Request::get_args('page'));
        $k = Request::get_args('k');
		$conditions = array();
		$conditions['goods.shop_id']=$this->my->id;
        if($k) {
		    $conditions['goods.goods_name like']="%{$k}%";
	    }		
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $tb = array('model' => 'goods',
 		            //'joins' => array('type'=>'left','table'=>'shoprequest','conditions'=>array('shopinfo.user_id' =>'shoprequest.user_id')),
				    'fields' => array('goods.*'),
					'conditions' => $conditions,
					'order' => 'goods.id desc',
					'limit' => '10',
					'group' => '',
					'url' => preg_replace("/&page=([^&]+)/","",$url_this),
					'page' => $page,
					'plist' => 6				
				); 
	    $result =  $this->fpage($tb); 		
		$this->set('k',$k);
		$this->set('result',$result);

	}

	public function filterAttr($haveArray,$postArray) {
		$array = array();
		foreach($haveArray as $key=>$value) {
			if(isset($postArray[$key])&&!empty($postArray[$key])) {
				if($postArray[$key] != $value) {
					$array['update'][$key] = $postArray[$key];
				}
				unset($postArray[$key]);
			} else {
				$array['delete'][$key] = $value;
			}
		}
		$array['insert'] = $postArray;
		return $array;
    }	
	
	public function edit($id) {	
        $this->_teamRights();	
		if (!empty($this->data)) {		
		    $post = array();
            $post['goods'] = array(
	            'goods_name'	=> Request::get_args('goods_name'),
	            'cat_id'		=> intval(Request::get_args('cat_id')),
	            'ucat_id'		=> intval(Request::get_args('ucat_id')),
	            'brand_id'		=> intval(Request::get_args('brand_id')),
	            'goods_intro'	=> Request::get_args('goods_intro'),
	            'goods_wholesale'=> Request::get_args('goods_wholesale'),
	            'goods_number'=> intval(Request::get_args('goods_number')),
	            'keyword'		=> Request::get_args('keyword'),
	            'goods_price'	=> Request::get_args('goods_price'),
	            'goods_refer_price'	=> Request::get_args('goods_refer_price'),				
	            'transport_price'	=> Request::get_args('transport_price'),
	            'is_on_sale'	=> intval(Request::get_args('is_on_sale')),
	            'is_best'		=> intval(Request::get_args('is_best')),
	            'is_new'		=> intval(Request::get_args('is_new')),
	            'is_hot'		=> intval(Request::get_args('is_hot')),
	            'is_promote'	=> intval(Request::get_args('is_promote')),
	            'type_id'		=> intval(Request::get_args('type_id')),
	            //'is_transport_template'=>intval($this->data["is_transport_template"]),
	            //'transport_template_id'=>intval($this->data["transport_template_id"]),
				'last_update_time'=>date("Y-m-d H:i:s",time()),
				'supplier_user_id'=>intval(Request::get_args('supplier_id'))				
            );
		    if(Request::get_args('ucat_id')) {			
			$filterAttr=array();
			$goods_id = intval($this->data["goods_id"]);

			$query = array(
					'fields' => array('goodsattr.*'),
					'conditions' => array('goodsattr.goods_id' => $goods_id),
					);	
            $goods_attr = POP::exe('[@@:UM goodsattr][@@:QU find:all]',$query);			
 			
            $have_attr = array();
            if($goods_attr) {
	            foreach($goods_attr as $v) {
				    $v = $v['goodsattr'];
		            $have_attr[$v['attr_id']] = $v['attr_values'];
	            }
            }			
            if($post['goods']['is_best']==1 || $post['goods']['is_new']==1 || $post['goods']['is_hot']==1 || $post['goods']['is_promote']==1){
	            $is_best=0;
	            $is_promote=0;
	            $is_new=0;
	            $is_hot=0;                		

				$query = array(
						'fields' => array('goods.*'),
						'conditions' => array('goods.shop_id' => $this->my->id),
						);	
				$rs = POP::exe('[@@:UM goods][@@:QU find:all]',$query);	

				
	            foreach ($rs as $val){
		            if(isset($val['goods']['goods_id'])){
			            if($val['goods']['is_best']==1){
				            $is_best++;
			            }
			            if($val['goods']['is_promote']==1){
				            $is_promote++;
			            }
			            if($val['goods']['is_new']==1){
				            $is_new++;
			            }
			            if($val['goods']['is_hot']==1){
				            $is_hot++;
			            }
		            }
	            }
	            if($is_best>=5){
		            $post['goods']['is_best']=0;
	            }
	            if($is_promote>=5){
		            $post['goods']['is_promote']=0;
	            }
	            if($is_new>=5){
		            $post['goods']['is_new']=0;
	            }
	            if($is_hot>=5){
		           $post['goods']['is_hot']=0;
	            }
            }			
		    $post_attr = Request::get_args('attr');	
            $filterAttr = $this->filterAttr($have_attr,$post_attr);
            Loader::import('lib.cupload');	
            $cupload = new upload();
            $cupload->set_dir(APP_ROOT . Param::read('upfiles.path') . '/goods/','{y}/{m}/{d}');
            $setthumb = array(
	            'width' => array(84,300),
	            'height' => array(84,300),
	            'name' => array('thumb','m')
            );
            $cupload->set_thumb($setthumb);			
	        $file = $cupload->execute();			
			$query = array(
					'fields' => array('shopinfo.*'),
					'conditions' => array('shopinfo.user_id' => $this->my->id),
					);	
            $shop_info = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);	

			
	        $row = $shop_info['shopinfo'];	
			$query = array(
					'fields' => array('userrank.*'),
					'conditions' => array('userrank.id' => $this->my->rank_id),
					);	
			$info = POP::exe('[@@:UM userrank][@@:QU find:first]',$query);			

			$privilege = unserialize($info['userrank']['privilege']);		
			if(isset($privilege[8])) {
				$Mcount = $privilege[8];
			}else {
				$Mcount = Param::read('upfiles.usersizelimit');		
			}				
	        if($row['count_imgsize']>$Mcount*1024*1024){
		        echo("上传图片已超过会员限定数，请清理后上传");
		        exit;
	        }	
			
	        if($file) {
		        $insert_array = array();
		        foreach($file as $k=>$v) {				
			        if($v['flag']==1) {
					    $rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
                        $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';					
				        $insert_array[$k]['img_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['m'];
				        $insert_array[$k]['thumb_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['thumb'];
				        $insert_array[$k]['img_original'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['name'];
				        $insert_array[$k]['is_set'] = '1';
				        $post['goods']['goods_thumb'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['thumb'];
				        $post['goods']['is_set_image'] = '1';	
				        $post1[$k]['uid']=$this->my->id;
				        $post1[$k]['img_size']=$v['size'];
				        $post1[$k]['upl_time'] = date("Y-m-d H:i:s",time());
				        $post1[$k]['img_url'] = $rootpath .str_replace(APP_ROOT,"",$v['dir']).$v['name'];

			        }
		        }
	            if(is_array($post1)){
		            $set = $value = $dot = '';
		            foreach($post1 as $key=>$val){
			            $row['count_imgsize']+=$val['img_size'];
			            $value .= $dot."(";
			            $dot = '';
			            foreach($val as $k1=>$v) {
				            if($key==0){
					            $set .= $dot."`$k1`";
				            }
				            $value .= $dot."'$v'";
				            $dot = ",";
			            }
			            $value .= ")";
		            }
		            $sql_part = "($set) values $value";
	            } else {
		            exit('insert_items not array');
	            }	
				$sql ="[@@:UM imgsize][@@:QU insert][_insert][_table imgsize:no] $sql_part";	
				$imgid= $suc =POP::exe($sql);					
	            if($suc){
	                $update_items=array();
		            $update_items['shopinfo']['count_imgsize']=$row['count_imgsize'];
					$query  = array();		
					$query['keyid'] = $row['id'];				
					$query['set'] = $update_items;					
					POP::exe('[@@:UM shopinfo][@@:QU save]',$query);						
	            }				
				//$insert_array[$k]['img_size_id'] = $imgid;			
	        }				

			$query = array(
					'fields' => array('goods.*'),
					'conditions' => array('goods.id' => $goods_id),
					);	
			$row = POP::exe('[@@:UM goods][@@:QU find:first]',$query);				
			
			$query  = array();		
			$query['keyid'] = $goods_id;				
			$query['set'] = $post;					
            if(POP::exe('[@@:UM goods][@@:QU save]',$query)) {			
	            ////如果修改后的商品分类和原来的商品分类不一样，则将原来的减一，新的加一
	            if($row['goods']['cat_id']!=$post['goods']['cat_id']){
		            //先将相应的分类中的商品数量删除
		            $flag = true;
		            $preid = $row['goods']['cat_id'];
		            while($flag){					
						$query  = array();		
						$query['keyid'] = true;
						$safeData['goodscategories'] = array('goods_num -'=>1);				
						$query['set'] = $safeData;	
						$query['conditions'] = array('goodscategories.cat_id'=>$preid);			
						POP::exe('[@@:UM goodscategories][@@:QU save]',$query);						

						$query = array(
								'fields' => array('goodscategories.*'),
								'conditions' => array('goodscategories.id' => $preid),
								);	
						$arry = POP::exe('[@@:UM goodscategories][@@:QU find:first]',$query);							

			            if($arry['goodscategories']['parent_id']!=0){
				            $preid=$arry['goodscategories']['parent_id'];
			            }else{
				            $flag = false;
			            }
		            }
		            //再将相应的分类中的商品数量增加
		            $flag = true;
		            $preid = $post['goods']['cat_id'];
		            while($flag){
						$query  = array();		
						$query['keyid'] = true;
						$safeData['goodscategories'] = array('goods_num +'=>1);				
						$query['set'] = $safeData;	
						$query['conditions'] = array('goodscategories.cat_id'=>$preid);			
						POP::exe('[@@:UM goodscategories][@@:QU save]',$query);							
						
						$query = array(
								'fields' => array('goodscategories.*'),
								'conditions' => array('goodscategories.id' => $preid),
								);	
						$arry = POP::exe('[@@:UM goodscategories][@@:QU find:first]',$query);						
						
			            if($arry['goodscategories']['parent_id']!=0){
				            $preid=$arry['goodscategories']['parent_id'];
			            }else{
				            $flag = false;
			            }
		            }
	            }

	            if(isset($filterAttr['insert'])&&!empty($filterAttr['insert'])) {			   
					$dot = '';
					$sql = "";
					foreach($filterAttr['insert'] as $key=>$value) {
						if($value) {
							if(is_array($value)) {
								$value = implode("\n",$value);
								$sql .= $dot . " ('$goods_id','$key','$value')";
								$dot = ',';
							} else {
								$sql .= $dot . " ('$goods_id','$key','$value')";
								$dot = ',';
							}
						}
					}
					$sql ="[@@:UM goodsattr][@@:QU insert][_insert][_table goodsattr:no] (goods_id,attr_id,attr_values) [_values {$sql}]";	
					POP::exe($sql);							
	            }

	            if(isset($filterAttr['update'])&&!empty($filterAttr['update'])) {
					foreach($filterAttr['update'] as $key=>$value) {
						if(is_array($value)) {
							$value = implode("\n",$value);
						}				
						$update_items=array();
						$update_items['goodsattr']['attr_values']=$value;
						$query  = array();		
						$query['keyid'] = true;				
						$query['set'] = $update_items;	
						$query['conditions'] = array('goodsattr.goods_id'=>$goods_id,'goodsattr.attr_id'=>$key);			
						POP::exe('[@@:UM goodsattr][@@:QU save]',$query);					
					}
	            }

	            if(isset($filterAttr['delete'])&&!empty($filterAttr['delete'])) {
					$attr_id = $dot = '';
					foreach($filterAttr['delete'] as $k=>$v) {
						$attr_id .= $dot.$k;
						$dot = ',';
					}

					$query = array('conditions'=>array('goodsattr.goods_id' => $goods_id,'goodsattr.attr_id' => $attr_id));			
					POP::exe('[@@:UM goodsattr][@@:QU del]',$query);					
					
	            }
	            if($file) {	// 如果需要更新图片
					$query  = array();		
					$query['keyid'] = true;				
					$query['set']['goodsgallery'] = array('is_set'=>0);	
					$query['conditions'] = array('goodsgallery.goods_id'=>$goods_id);			
					POP::exe('[@@:UM goodsgallery][@@:QU save]',$query);				

					if(!empty($insert_array)) {

						foreach($insert_array as $v) {
							$insert_items = $v;
							$insert_items['goods_id'] = $goods_id;
							$postdo = array();
							$postdo['goodsgallery'] = $insert_items;
							POP::exe('[@@:UM goodsgallery][@@:QU save]',$postdo);					
						}		
					}
	            }
				
			    $this->flash('修改成功！', Router::url('goods/edit/'.$goods_id));
            } else {
	            $this->flash('修改失败！', Router::url('goods/edit/'.$goods_id));
            }
			} else {
			   $this->flash('请选择店铺商品分类！', Router::url('goods/edit/'.$goods_id));
			}			
		}else
		{
		    $goods_id = intval($id);

			$query = array(
					'fields' => array('goods.*'),
					'conditions' => array('goods.shop_id' => $this->my->id,'goods.id'=>$goods_id),
					);	
			$goods_info = POP::exe('[@@:UM goods][@@:QU find:first]',$query);			
			
            if(empty($goods_info)) {
	            exit( '商品不存在');
            }		

			$query = array(
					'fields' => array('goodscategories.*'),
					'order' => 'sort_order asc,id asc'
					);	
		    $category_info = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);			

			
            $select_category_name="";
            $asd_id=1;
            $test1=0;
            foreach($category_info as $value) {
	            if($goods_info['goods']['cat_id']==$value['goodscategories']['id']) {
		            $select_category_name = $value['goodscategories']['cat_name'];
		            $asd_id= $value['goodscategories']['parent_id'];
		            $test1=$value['goodscategories']['id'];
		            if($asd_id!=0){
			            $test1=$asd_id;
		            }
		            break;
	            }
            }

            if($asd_id!=0){
	            foreach($category_info as $value) {
		            if($asd_id==$value['goodscategories']['id']) {
			            $select_category_name = $value['goodscategories']['cat_name']." > ".$select_category_name;
			            $asd_id= $value['goodscategories']['parent_id'];
			            if($asd_id!=0){
				            $test1=$asd_id;
			            }
			            break;
		            }
	            }
            }
            if($asd_id!=0){
	            foreach($category_info as $value) {
		            if($asd_id==$value['goodscategories']['id']) {
			            $select_category_name = $value['goodscategories']['cat_name']." > ".$select_category_name;
			            $asd_id= $value['goodscategories']['parent_id'];
			            if($asd_id!=0){
				           $test1=$asd_id;
			            }
			            break;
		            }
	            }
            }
            if($asd_id!=0){
	            foreach($category_info as $value) {
		            if($asd_id==$value['goodscategories']['id']) {
			            $select_category_name = $value['goodscategories']['cat_name']." > ".$select_category_name;
			            $asd_id= $value['goodscategories']['parent_id'];
			            if($asd_id!=0){
				            $test1=$asd_id;
			            }
			            break;
		            }
	            }
            }
			$query = array(
					'fields' => array('shopusercategorie.*'),
					'conditions' => array('shopusercategorie.shop_id' => $this->my->id),
					'order' => 'sort_order asc'
					);	
            $shop_category = POP::exe('[@@:UM shopusercategorie][@@:QU find:all]',$query);	


            $html_shop_category = $this->html_format_shop_category($shop_category,$goods_info['goods']['ucat_id']);			
            $attribute_info = array();
            if($goods_info['goods']['cat_id']) {

				$query = array(
						'fields' => array('attribute.*'),
						'conditions' => array('attribute.cat_id' => $goods_info['goods']['cat_id']),
						'order' => 'sort_order asc'
						);	
				$result = POP::exe('[@@:UM attribute][@@:QU find:all]',$query);					
				
				
	            $array = array();
	            if($result) {
		            $i = 0;
		            foreach($result as $k=>$v) {
			            $array[$i]['attr_id'] = $v['attribute']['id'];
			            $array[$i]['attr_name'] = iconv('GB2312','UTF-8' , $v['attribute']['attr_name']);
			            $array[$i]['input_type'] = $v['attribute']['input_type'];
			            $array[$i]['attr_values'] = iconv('GB2312','UTF-8' , $v['attribute']['attr_values']);
			            $i++;
		            }
	            }		
	            $attribute_info = $array;
            }
            $js_attribute_info = json_encode($attribute_info);

			$query = array(
					'fields' => array('goodsattr.*'),
					'conditions' => array('goodsattr.goods_id' => $goods_id),
					);	
			$goods_attr = POP::exe('[@@:UM goodsattr][@@:QU find:all]',$query);				

			
		    $isset_payment = 1;

			$url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
			$tb = array('model' => 'imgsize',
						'fields' => array("imgsize.*"),
						'conditions' => array('imgsize.goods_id'=>$goods_id),
						'order' => '',
						'limit' => '10',
						'group' => '',
						'url' => preg_replace("/&page=([^&]+)/","",$url_this),
						'page' => 1,
						'plist' => 6				
					); 
			$result =  $this->fpage($tb); 			
			
            $imagelistid="";
            if(isset($result['data'])&&!empty($result['data'])){
	            foreach ($result['data'] as $v){
		            $imagelistid.=$v['imgsize']['id'].",";
	            }
	            if($imagelistid){
		            $imagelistid=substr($imagelistid,0,strlen($imagelistid)-1);
	            }
            }

			$query = array(
					'fields' => array('supplier.*'),
					'conditions' => array('supplier.shop_id' => $this->my->id),
					);	
			$supplierlist = POP::exe('[@@:UM supplier][@@:QU find:all]',$query);	

			
	        $this->set('supplierlist',$supplierlist);			

			$query = array(
					'fields' => array('goodstransport.*'),
					'conditions' => array('goodstransport.shop_id' => $this->my->id),
					'order'=>' id DESC '
					);	
			$transport_template_list = POP::exe('[@@:UM goodstransport][@@:QU find:all]',$query);			
			
			
	        $this->set('transport_template_list',$transport_template_list);			
	        $this->set('ps',$this->C_session->id());			
            $this->set('goods_id',$goods_id);
            $this->set('select_category_name',$select_category_name);
            $this->set('goods_info',$goods_info);			
            $this->set('html_shop_category',$html_shop_category);			
            $this->set('result',$result);
            $this->set('imagelistid',$imagelistid);
            $this->set('category_info',$category_info);
            $this->set('goods_attr',$goods_attr);	
            $this->set('js_attribute_info',$js_attribute_info);			
            $this->set('test1',$test1);	
	        $this->set('isset_payment',1);			
		}		
	}
	
	public function add($id=null) {
        $this->_teamRights();
 		if (!empty($this->data)) {
		    $post = array();
            $post['goods'] = array(
	            'goods_name'	=> Request::get_args('goods_name'),
	            'cat_id'		=> intval(Request::get_args('cat_id')),
	            'ucat_id'		=> intval(Request::get_args('ucat_id')),
	            'brand_id'		=> intval(Request::get_args('brand_id')),
	            'goods_intro'	=> Request::get_args('goods_intro'),
	            'goods_wholesale'=> Request::get_args('goods_wholesale'),
	            'goods_number'=> intval(Request::get_args('goods_number')),
	            'keyword'		=> Request::get_args('keyword'),
	            'goods_price'	=> Request::get_args('goods_price'),
	            'goods_refer_price'	=> Request::get_args('goods_refer_price'),				
	            'transport_price'	=> Request::get_args('transport_price'),
	            'is_on_sale'	=> intval(Request::get_args('is_on_sale')),
	            'is_best'		=> intval(Request::get_args('is_best')),
	            'is_new'		=> intval(Request::get_args('is_new')),
	            'is_hot'		=> intval(Request::get_args('is_hot')),
	            'is_promote'	=> intval(Request::get_args('is_promote')),
	            'type_id'		=> intval(Request::get_args('type_id')),
	            //'is_transport_template'=>intval($this->data["is_transport_template"]),
	            //'transport_template_id'=>intval($this->data["transport_template_id"]),
				'shop_id'=>$this->my->id,
				'add_time'=>date("Y-m-d H:i:s",time()),
				'supplier_user_id'=>intval(Request::get_args('supplier_id'))				
            );	
		    if(Request::get_args('ucat_id')) {
            $image_size_id=Request::get_args("image_size_id");
		    $post_attr = Request::get_args('attr');
            Loader::import('lib.cupload');
	
            $cupload = new upload();
            $cupload->set_dir(APP_ROOT . Param::read('upfiles.path') . '/goods/','{y}/{m}/{d}');
            $setthumb = array(
	            'width' => array(84,300),
	            'height' => array(84,300),
	            'name' => array('thumb','m')
            );
            $cupload->set_thumb($setthumb);
			$query = array(
					'fields' => array('shopinfo.*'),
					'conditions' => array('shopinfo.user_id' => $this->my->id),
					);	
            $shop_info = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);				
			
			
	        $row = $shop_info['shopinfo'];	
			$goods_num=$row['goods_num']+1;
			$update_items =array();
		    $update_items['shopinfo']['goods_num']=$goods_num;
			$query  = array();		
			$query['keyid'] = true;				
			$query['set'] = $update_items;	
			$query['conditions'] = array('shopinfo.id'=>$row['id']);			
			POP::exe('[@@:UM shopinfo][@@:QU save]',$query);				
			
			$query = array(
					'fields' => array('userrank.*'),
					'conditions' => array('userrank.id' => $this->my->rank_id),
					);	
			$info = POP::exe('[@@:UM userrank][@@:QU find:first]',$query);
	
			$privilege = unserialize($info['userrank']['privilege']);		
			if(isset($privilege[8])) {
				$Mcount = $privilege[8];
			}else {
				$Mcount = Param::read('upfiles.usersizelimit');		
			}			
	        if($row['count_imgsize']>$Mcount*1024*1024){
		        echo("上传图片已超过会员限定数，请清理后上传");
		        exit;
	        }
            $imgid='';			
	        $file = $cupload->execute();
	        if(count($file)) {
		        $insert_array = array();
		        foreach($file as $k=>$v) {
			        if($v['flag']==1) {
					    $rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
                        $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';						
				        $insert_array[$k]['img_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['m'];
				        $insert_array[$k]['thumb_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['thumb'];
				        $insert_array[$k]['img_original'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['name'];
				        $insert_array[$k]['is_set'] = '1';
				        $post['goods']['goods_thumb'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['thumb'];
				        $post['goods']['is_set_image'] = '1';	
				        $post1[$k]['uid']=$this->my->id;
				        $post1[$k]['img_size']=$v['size'];
				        $post1[$k]['upl_time'] = date("Y-m-d H:i:s",time());
				        $post1[$k]['img_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['name'];
	                    if(is_array($post1)){
		                    $set = $value = $dot = '';
		                    foreach($post1 as $key=>$val){
			                    $row['count_imgsize']+=$val['img_size'];
			                    $value .= $dot."(";
			                    $dot = '';
			                    foreach($val as $k1=>$v) {
				                    if($key==0){
					                    $set .= $dot."`$k1`";
				                    }
				                    $value .= $dot."'$v'";
				                    $dot = ",";
			                    }
			                    $value .= ")";
		                    }
		                    $sql_part = "($set) values $value";
	                    } else {
		                    exit('insert_items not array');
	                    }	
						$sql ="[@@:UM imgsize][@@:QU insert][_insert][_table imgsize:no] $sql_part";	
						$imgid= $suc =POP::exe($sql);						

	                    if($suc){
	                        $update_items=array();
		                    $update_items['shopinfo']['count_imgsize']=$row['count_imgsize'];
							$query  = array();		
							$query['keyid'] = true;				
							$query['set'] = $update_items;	
							$query['conditions'] = array('shopinfo.id'=>$row['id']);			
							POP::exe('[@@:UM shopinfo][@@:QU save]',$query);	
	                    }				
				        $insert_array[$k]['img_size_id'] = $imgid;
			        }
		        }
	        }		
	
            if($post['goods']['is_best']==1 || $post['goods']['is_new']==1 || $post['goods']['is_hot']==1 || $post['goods']['is_promote']==1){
	            $is_best=0;
	            $is_promote=0;
	            $is_new=0;
	            $is_hot=0;
	
				$query = array(
						'fields' => array('goods.*'),
						'conditions' => array('goods.shop_id' => $this->my->id),
						);	
				$rs = POP::exe('[@@:UM goods][@@:QU find:all]',$query);				
				
				
	            foreach ($rs as $val){
		            if(isset($val['goods']['goods_id'])){
			            if($val['goods']['is_best']==1){
				            $is_best++;
			            }
			            if($val['goods']['is_promote']==1){
				            $is_promote++;
			            }
			            if($val['goods']['is_new']==1){
				            $is_new++;
			            }
			            if($val['goods']['is_hot']==1){
				            $is_hot++;
			            }
		            }
	            }
	            if($is_best>=5){
		            $post['goods']['is_best']=0;
	            }
	            if($is_promote>=5){
		            $post['goods']['is_promote']=0;
	            }
	            if($is_new>=5){
		            $post['goods']['is_new']=0;
	            }
	            if($is_hot>=5){
		           $post['goods']['is_hot']=0;
	            }
            }
            $goods_id = POP::exe('[@@:UM goods][@@:QU save]',$post);
            if($goods_id) {

	            //更新商品默认运费信息
	            //update_default_transportprice($dbo,$t_goods,$t_transport_template,$goods_id);
	            if(!empty($post_attr)) {
					$dot = '';
					$sql = "";
					foreach($post_attr as $key=>$value) {
						if($value) {
							if(is_array($value)) {
								$value = implode("\n",$value);
								$sql .= $dot . " ('$goods_id','$key','$value')";
								$dot = ',';
							} else {
								$sql .= $dot . " ('$goods_id','$key','$value')";
								$dot = ',';
							}
						}
					}	
					$sql ="[@@:UM goodsattr][@@:QU insert][_insert][_table goodsattr:no] (goods_id,attr_id,attr_values) [_values {$sql}]";	
					POP::exe($sql);						
                }				
	            //商品分类表，每个商品分类下面有多少商品,包括子分类
	            $flag = true;
	            $preid = $post['goods']['cat_id'];
	            while($flag){
					$query  = array();		
					$query['keyid'] = true;
					$safeData['goodscategories'] = array('goods_num +'=>1);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('goodscategories.id'=>$preid);			
					POP::exe('[@@:UM goodscategories][@@:QU save]',$query);	

					$query = array(
							'fields' => array('goodscategories.*'),
							'conditions' => array('goodscategories.id' => $preid),
							);	
					$row = POP::exe('[@@:UM goodscategories][@@:QU find:first]',$query);
		            if($row['goodscategories']['parent_id']!=0){
			            $preid=$row['goodscategories']['parent_id'];
		            }else{
			            $flag = false;
		            }
	            }
				
				$query  = array();		
				$query['keyid'] = true;				
				$query['set']['imgsize'] = array('goods_id'=>$goods_id);	
				$query['conditions'] = array('imgsize.id'=>explode(',', $image_size_id));			
				POP::exe('[@@:UM imgsize][@@:QU save]',$query);
				
	            if(count($file)) {
	                if(!empty($insert_array)) {
	                    $i = 0;
	                    foreach($insert_array as $v) {
		                    $insert_items = $v;
		                    $insert_items['goods_id'] = $goods_id;
		                    $postdo = array();
		                    $postdo['goodsgallery'] = $insert_items;
		                    if(POP::exe('[@@:UM goodsgallery][@@:QU save]',$postdo)	){		
			                    $i++;
		                    }
	                    }	   
	                }
	            }
				$this->flash('添加成功！', Router::url('goods/ulist'));
            } else {
	            $this->flash('添加失败！', Router::url('goods/add'));
            }
			} else {
			   $this->flash('请选择店铺商品分类！', Router::url('goods/add'));
			}

		}else { 

			$query = array(
					'fields' => array('supplier.*'),
					'conditions' => array('supplier.shop_id' => $this->my->id)
					);	
		    $supplierlist = POP::exe('[@@:UM supplier][@@:QU find:all]',$query);


			$query = array(
					'fields' => array('goodstransport.*'),
					'conditions' => array('goodstransport.shop_id' => $this->my->id),
					'order'=>' id DESC '
					);	
			$transport_template_list = POP::exe('[@@:UM goodstransport][@@:QU find:all]',$query);	


            //店铺已经上传的产品数量	
			$query = array(
				'conditions' => array('goods.shop_id' => $this->my->id), 
			);
            $this_shop_goods_num = POP::exe('[@@:UM goods][@@:QU find:count]',$query);	
            		
            $goods_info = array(
	            'goods_name'	=> '',
	            'cat_id'		=> 0,
	            'ucat_id'		=> 0,
	            'goods_intro'	=> '',
	            'goods_number'	=> 99,
	            'keyword'		=> '',
	            'goods_price'	=> '0.00',
	            'is_on_sale'	=> 1,
	            'is_best'		=> 0,
	            'is_new'		=> 0,
	            'is_hot'		=> 0,
	            'is_promote'	=> 0,
	            'goods_wholesale'=> '',
	            'transport_price'=> '0.00',
				'supplier_user_id'=>'0'
            );		

			$query = array(
					'fields' => array('goodscategories.*'),
					'order'=>'sort_order asc,id asc'
					);	
            $category_info = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);			
			
			
			
			$query = array(
					'fields' => array('shopusercategorie.*'),
					'conditions' => array('shopusercategorie.shop_id' => $this->my->id),
					'order' => 'sort_order asc'
					);	
            $shop_category = POP::exe('[@@:UM shopusercategorie][@@:QU find:all]',$query);	


            $html_shop_category = $this->html_format_shop_category($shop_category,$goods_info['ucat_id']);		
		
	        $this->set('ps',$this->C_session->id());
	        $this->set('supplierlist',$supplierlist);			
	        $this->set('goods_info',$goods_info);
	        $this->set('category_info',$category_info);	
	        $this->set('html_shop_category',$html_shop_category);			
	        $this->set('transport_template_list',$transport_template_list);
	        $this->set('isset_payment',1);			
		}

	}

	public function gallery($goods_id,$updata='') {
        $this->_teamRights();	
        $goods_id = intval($goods_id);
        if(!$goods_id) {
	        trigger_error("非法操作");
        }
		if(isset($this->my->id)){$user_id = $this->my->id; }else{ $user_id = 0 ;}		

		$query = array(
				'fields' => array('goods.*'),
				'conditions' => array('goods.shop_id' => $user_id,'goods.id'=>$goods_id),
				);	
        $goods = POP::exe('[@@:UM goods][@@:QU find:first]',$query);		
		
		
		if(empty($goods)) {
		    $this->flash('该产品不存在！', Router::url('goods/ulist'));
		}	
        if($goods['goods']['lock_flg']==1) { trigger_error("此商品已被锁定");}//锁定	
        if($user_id > 0){
            if($this->my->locked==1){
	            $this->C_session->destroy();
	            exit("您已经被锁定了");//非法操作
            }
        }	
		$shop_id = $user_id;
	    $this->loadModel('goodsgallery'); 		
		if($updata=='updata') {
			$query = array(
					'fields' => array('shopinfo.*'),
					'conditions' => array('shopinfo.user_id' => $this->my->id),
					);	
            $shop_info = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);			
			
			
	        $row = $shop_info['shopinfo'];			     
			// 更新老图片的描述
            $old_img_desc = array();
            if(Request::get_args('old_img_desc')) {
	            foreach(Request::get_args('old_img_desc') as $k=>$v) {
		            $old_img_desc[$k] = $v;
	            }
            }
            if(!empty($old_img_desc)) {
	            foreach($old_img_desc as $k=>$v) {
					$query  = array();		
					$query['keyid'] = true;				
					$query['set']['goodsgallery'] = array('img_desc'=>$v);	
					$query['conditions'] = array('goodsgallery.goods_id'=>$goods_id,'goodsgallery.id'=>$k);			
					POP::exe('[@@:UM goodsgallery][@@:QU save]',$query);				
	            }			
            }	

            Loader::import('lib.cupload');
	
            $cupload = new upload();
            $cupload->set_dir(APP_ROOT . Param::read('upfiles.path') . '/goods/','{y}/{m}/{d}');
            $setthumb = array(
	            'width' => array(84,300),
	            'height' => array(84,300),
	            'name' => array('thumb','m')
            );
            $cupload->set_thumb($setthumb);	
            $file = $cupload->execute();
            $img_desc = array();
            foreach(Request::get_args('img_desc') as $k=>$v) {
	            $img_desc[$k] = $v;
            }
			$query = array(
					'fields' => array('userrank.*'),
					'conditions' => array('userrank.id' => $this->my->rank_id),
					);	
			$info = POP::exe('[@@:UM userrank][@@:QU find:first]',$query);
			$privilege = unserialize($info['userrank']['privilege']);		
			if(isset($privilege[8])) {
				$Mcount = $privilege[8];
			}else {
				$Mcount = Param::read('upfiles.usersizelimit');		
			}			
	        if($row['count_imgsize']>$Mcount*1024*1024){
		        echo("上传图片已超过会员限定数，请清理后上传");
		        exit;
	        }
			
            if($file) {
	            $insert_array = array();
	            foreach($file as $k=>$v) {
		            if($v['flag']==1) {
					    $rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
                        $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';					
				        $insert_array[$k]['img_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['m'];
				        $insert_array[$k]['thumb_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['thumb'];
				        $insert_array[$k]['img_original'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['name'];
			            $insert_array[$k]['img_desc'] = $img_desc[$k];
			
				        $post1['uid']=$this->my->id;
				        $post1['img_size']=$v['size'];
				        $post1['upl_time'] = date("Y-m-d H:i:s",time());
				        $post1['img_url'] = $rootpath.str_replace(APP_ROOT,"",$v['dir']).$v['name'];
 		                $postdo = array();
		                $postdo['imgsize'] = $post1;                       
						if($img_id = POP::exe('[@@:UM imgsize][@@:QU save]',$postdo)) {
	                        $update_items=array();
		                    $update_items['shopinfo']['count_imgsize']=$row['count_imgsize']+$v['size'];
							$query  = array();		
							$query['keyid'] = true;				
							$query['set'] = $update_items;	
							$query['conditions'] = array('shopinfo.id'=>$shop_id);			
							POP::exe('[@@:UM shopinfo][@@:QU save]',$query);

							
						}
			            $insert_array[$k]['img_size_id'] = $img_id;
						
		            }
	            }				
	            if(!empty($insert_array)) {
	                $i = 0;
	                foreach($insert_array as $v) {
		                $insert_items = $v;
		                $insert_items['goods_id'] = $goods_id;
		                $postdo = array();
		                $postdo['goodsgallery'] = $insert_items;
		                if(POP::exe('[@@:UM goodsgallery][@@:QU save]',$postdo)){		
			                $i++;
		                }
	                }	   
	            }					
            }
			$this->flash("商品图片更新成功！", Router::url('goods/gallery/'.$goods_id)); 
			
		} else {		

			$query = array(
					'fields' => array('goodsgallery.*'),
					'conditions' => array('goodsgallery.goods_id' => $goods_id),
					);	
			$gallery_list = POP::exe('[@@:UM goodsgallery][@@:QU find:all]',$query);			
			
			
	        $this->set('gallery_list',$gallery_list);
	        $this->set('goods_id',$goods_id);
        }		
		
	}	

	public function galleryset() {	
        $img_id = intval(Request::get_args('id'));
        $goods_id = intval(Request::get_args('gid'));	
        if(!$goods_id || !$img_id) {
	        exit();
        }
		$shop_id = $this->my->id;

		$query = array(
				'fields' => array('goods.*'),
				'conditions' => array('goods.shop_id' => $shop_id,'goods.id'=>$goods_id),
				);	
        $goods_info = POP::exe('[@@:UM goods][@@:QU find:first]',$query);			
		
        if(empty($goods_info['goods']['id'])) { exit(); }			

		$query = array(
				'fields' => array('goodsgallery.*'),
				'conditions' => array('goodsgallery.goods_id' => $goods_id,'goodsgallery.id' => $img_id),
				);	
		$result = POP::exe('[@@:UM goodsgallery][@@:QU find:first]',$query);		
		
		
        if($result) {
	        $goods_thumb = $result['goodsgallery']['thumb_url'];
        } else {
	        exit("非法操作");
        }
		
        // 获取老的已设为首图的img_id
        $old_set_img_id = '';

		$query = array(
				'fields' => array('goodsgallery.*'),
				'conditions' => array('goodsgallery.goods_id' => $goods_id,'goodsgallery.is_set' => 1),
				);	
		$result = POP::exe('[@@:UM goodsgallery][@@:QU find:first]',$query);
		
        if($result) {
	        $old_set_img_id = $result['goodsgallery']['id'];
        }		

		$query  = array();		
		$query['keyid'] = true;				
		$query['set']['goodsgallery'] = array('is_set'=>1);	
		$query['conditions'] = array('goodsgallery.goods_id'=>$goods_id,'goodsgallery.id'=>$img_id);			
        if(POP::exe('[@@:UM goodsgallery][@@:QU save]',$query)) {
		    $nowtime = date("Y-m-d H:i:s",time()) ;
			$query  = array();		
			$query['keyid'] = true;				
			$query['set']['goods'] = array('is_set_image'=>1,'goods_thumb'=>$goods_thumb,'last_update_time'=>$nowtime);	
			$query['conditions'] = array('goods.shop_id'=>$shop_id,'goods.id'=>$goods_id);			
			POP::exe('[@@:UM goods][@@:QU save]',$query);			

	        if($old_set_img_id) {
				$query  = array();		
				$query['keyid'] = true;				
				$query['set']['goodsgallery'] = array('is_set'=>0);	
				$query['conditions'] = array('goodsgallery.goods_id'=>$goods_id,'goodsgallery.id'=>$old_set_img_id);			
				POP::exe('[@@:UM goodsgallery][@@:QU save]',$query);			
	        }
			$this->flash('首图设置成功！', Router::url('goods/gallery/'.$goods_id));
        } else {
			$this->flash('首图设置失败，请重试！', Router::url('goods/gallery/'.$goods_id));		
        }
	
	}	
	
	public function gallerydrop() {		
        $id = intval(Request::get_args('id'));
        $gid = intval(Request::get_args('gid'));
        $unset_image = intval(Request::get_args('s'));
        if(!$id || !$gid) {
	        exit();
        }
		$shop_id = $this->my->id;
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));

		$query = array(
				'fields' => array('goodsgallery.*'),
				'conditions' => array('goodsgallery.goods_id' => $gid,'goodsgallery.id' => $id),
				);	
		$gallery_info = POP::exe('[@@:UM goodsgallery][@@:QU find:first]',$query);			

        if(empty($gallery_info)) { exit(); }

		$query = array(
				'fields' => array('goods.*'),
				'conditions' => array('goods.shop_id' => $shop_id,'goods.id'=>$gid),
				);	
        $goods_info = POP::exe('[@@:UM goods][@@:QU find:first]',$query);		
		
		
        if(empty($goods_info['goods']['is_set_image'])) { exit(); }		
	    $row = $gallery_info['goodsgallery'];
        $img_size = '';
        if($row){
	        $img_size_id = $row['img_size_id'];
			
			$query = array(
					'fields' => array('imgsize.*'),
					'conditions' => array('imgsize.id' => $img_size_id),
					);	
			$rs = POP::exe('[@@:UM imgsize][@@:QU find:first]',$query);			
			
		    $count_imgsize=$rs['imgsize']['img_size'];

			$query = array('keyid'=>$img_size_id);			
		    if(POP::exe('[@@:UM imgsize][@@:QU del]',$query)){
			    //删除图片
			    @unlink($v['img_url']);
			    @unlink($v['thumb_url']);
			    @unlink($v['img_original']);
		    }
	        //删除goods_gallery表中的数据
	        $img_id = $row['id'];
			$query = array('keyid'=>$img_id);			
			POP::exe('[@@:UM goodsgallery][@@:QU del]',$query);			
	        //修改shop_info中的数据
			$query  = array();		
			$query['keyid'] = true;				
			$query['set']['shopinfo'] = array('count_imgsize -'=>$count_imgsize);	
			$query['conditions'] = array('shopinfo.id'=>$shop_id);			
			POP::exe('[@@:UM shopinfo][@@:QU save]',$query);			
	        if($unset_image==1) {
				$query  = array();		
				$query['keyid'] = true;				
				$query['set']['goods'] = array('is_set_image'=>0,'goods_thumb'=>'');	
				$query['conditions'] = array('goods.id'=>$gid,'goods.shop_id'=>$shop_id);			
				POP::exe('[@@:UM goods][@@:QU save]',$query);			
	        }
	        echo '1';
        }else{
	        echo '0';
        }
		exit;
	}	
	
	public function del($id) {
        $this->_teamRights();	

		$query = array(
				'fields' => array('goods.*'),
				'conditions' => array('goods.shop_id' => $this->my->id,'goods.id'=>$id),
				);	
		$rs = POP::exe('[@@:UM goods][@@:QU find:first]',$query);			
		
		if(empty($rs)) {
		    $this->flash('该产品不存在！', Router::url('goods/ulist'));
		}else {

			$query = array(
					'fields' => array('goodsgallery.*'),
					'conditions' => array('goodsgallery.goods_id' => $id),
					);	
			$row = POP::exe('[@@:UM goodsgallery][@@:QU find:first]',$query);	
			
            $count_imgsize=0;
			if(!empty($row)){
                foreach($row as $v){
	                if($v['goods_id']==$id){
		                $img_size_id = $v['img_size_id'];

						$query = array(
								'fields' => array('imgsize.*'),
								'conditions' => array('imgsize.id' => $img_size_id),
								);	
						$rs = POP::exe('[@@:UM imgsize][@@:QU find:first]',$query);						

		                $count_imgsize+=$rs['imgsize']['img_size'];
						$query = array('keyid'=>$img_size_id);			
		                if(POP::exe('[@@:UM imgsize][@@:QU del]',$query)){
			                //删除图片
			                @unlink($v['img_url']);
			                @unlink($v['thumb_url']);
			                @unlink($v['img_original']);
		                }
	                }
	                $img_id = $v['id'];
					$query = array('keyid'=>$img_id);			
					POP::exe('[@@:UM goodsgallery][@@:QU del]',$query);					
					
                }
			}

			$query = array('conditions'=>array('goodsattr.goods_id' => $id));			
			POP::exe('[@@:UM goodsattr][@@:QU del]',$query);	
				
			$query = array(
					'fields' => array('shopinfo.*'),
					'conditions' => array('shopinfo.id' => $this->my->id),
					);	
			$row = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);	


			
            $goods_num=$row['shopinfo']['goods_num']-1;
            $count_imgsize = $row['shopinfo']['count_imgsize'] - $count_imgsize;

	        $update_items=array();
		    $update_items['shopinfo']['count_imgsize']=$count_imgsize;
		    $update_items['shopinfo']['goods_num']=$goods_num;			
			$query  = array();		
			$query['keyid'] = true;				
			$query['set'] = $update_items;	
			$query['conditions'] = array('shopinfo.id'=>$this->my->id);			
			POP::exe('[@@:UM shopinfo][@@:QU save]',$query);
			
			$query = array('keyid'=>$id);			
            if(POP::exe('[@@:UM goods][@@:QU del]',$query)) {			    
			    $this->flash('删除成功！', Router::url('goods/ulist'));
			} else {
			    $this->flash('删除失败！', Router::url('goods/ulist'));
			}			
		}

			
	}	
	
    function html_format_shop_category($array,$value,$parentid=0,$level=0) {
	    $str = '';
	    $str_pad = $this->getnbsp($level);

	    foreach($array as $v) {
		    $selected = '';
		    if($v['shopusercategorie']['parent_id'] == $parentid) {
			    if($value == $v['shopusercategorie']['id']) { $selected = 'selected';}
			    $str .= "<option value='".$v['shopusercategorie']['id']."' ".$selected.">".$str_pad.$v['shopusercategorie']['shop_cat_name']."</option>";
			    $str .= $this->html_format_shop_category($array,$value,$v['shopusercategorie']['id'],($level+1));
		    }
	    }
	    return $str;
    }

	public function getcatlist() {	
        $cat_id = intval($_POST['cat_id']);	
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));		

		$query = array(
				'fields' => array('goodscategories.*'),
				'conditions' => array('goodscategories.parent_id' => $cat_id),
				'order' => 'sort_order asc,id asc'
				);	
		$category_list = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);			
		
		
        if(!$category_list) {
	        exit("-1");
        }

        $return_array = array();
        $i = 0;
        foreach($category_list as $value) {
	        $return_array[$i]['cat_id'] = $value['goodscategories']['id'];
	        $return_array[$i]['cat_name'] = iconv('GB2312','UTF-8' , $value['goodscategories']['cat_name']);
	        $i++;
        }
        echo json_encode($return_array);
		exit;
	}	

	public function getucategoryadd() {	

        $post['shopusercategorie']['shop_cat_name'] = iconv('UTF-8','GB2312' , $_POST['name']);
        $post['shopusercategorie']['parent_id'] = 0;
        $post['shopusercategorie']['shop_cat_unit'] = '';
        $post['shopusercategorie']['sort_order'] = '0';
        $post['shopusercategorie']['shop_id'] = $this->my->id;
        if(empty($post['shopusercategorie']['shop_cat_name'])) {
	        exit("-1");
        }	
		$id = POP::exe('[@@:UM shopusercategorie][@@:QU save]',$post);				
        if($id) {
	        echo $id;
	        exit();
        } else {
	        exit("-1");
        }		
	}		

	
	public function getshopimgselect() {
        $ii = 2;
        if(!isset($_POST['page']))	$_POST['page'] =1;	
        $page =intval($_POST['page']);	
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));		

		$url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
		$tb = array('model' => 'imgsize',
					'fields' => array("imgsize.*"),
					'conditions' => array('imgsize.uid'=>$this->my->id),
					'order' => '',
					'limit' => '10',
					'group' => '',
					'url' => preg_replace("/&page=([^&]+)/","",$url_this),
					'page' => $page,
					'plist' => 6				
				); 
		$result =  $this->fpage($tb);		
		
		
		
		$str= "<ul>";
		$i=1;
		$vala="";
		if (!empty($result['data'])){
		foreach($result['data'] as $val){
			if($ii==2){
				$str.= "<li><p class='photo'><img src='".$val['imgsize']['img_url']."' width='100' height='100' /></p>";
				$str.="<p><a href='javascript:;'  onclick='change_style(\"style1\");return addIntroImg(this);' >插入</a><a href='javascript:;' name='".$val['imgsize']["id"]."' onclick='return delIntroImg(this)'>删除</a></p></li>";
			}else
			if($ii==1){
				$str.= "<td><img ondblclick=\"showimg('".$val['imgsize']['img_url']."')\" src='".$val['imgsize']['img_url']."' height='100' width='100'/></td>";
			}
			$vala.=$val['imgsize']["id"].",";
			if($i%6==0){
				$str.="<li></li>";
			}
			$i++;
		}
		}
		$str.="</ul>";
		if($vala){
			$vala=substr($vala,0,strlen($vala)-1);
		}
		$str="<span style='display:none'>$vala</span>".$str;

		$start_page	=	1;
		$end_page	=	10;
		$first_page	=	0;
		$last_page	=	0;
	
		if($this->params['paging']['imgsize']['pageCount']	>	10){
			if($this->params['paging']['imgsize']['page']	>	5){
				$start_page	=	$this->params['paging']['imgsize']['page']	-	4;
				$end_page	=	$this->params['paging']['imgsize']['page']	+	5;
			}
			if($end_page	>	$this->params['paging']['imgsize']['pageCount'])
			{
				$start_page	=	$this->params['paging']['imgsize']['pageCount']	-	9;
				$end_page	=	$this->params['paging']['imgsize']['pageCount'];
			}
		}else{
			$end_page	=	$this->params['paging']['imgsize']['pageCount'];
		}
		if($start_page	>	1)
			$first_page	=	1;
		if($end_page	<	$this->params['paging']['imgsize']['pageCount'])
			$last_page	=	1;
		if(isset($this->params['paging']['imgsize']['pageCount'])){
			$pagecount=$this->params['paging']['imgsize']['pageCount'];
		}
		$test="";
		if($this->params['paging']['imgsize']['pageCount']>0){
			$test.="<a class='upPage' onclick='get_img_list(\"img_select3\",\"2\",\"img_list3\",".($this->params['paging']['imgsize']['page'] -1 ) .")' href='javascript:;'>上一页</a>";
			if($first_page==1){
				$test.="<a onclick='get_img_list(\"img_select3\",\"2\",\"img_list3\",1)' href='javascript:;' >1</a><span>...</span>";
			}
			for($i=$start_page;$i<=$end_page;$i++){
				if($i==$this->params['paging']['imgsize']['page']){
					$test.="<a class='num now' onclick='get_img_list(\"img_select3\",\"2\",\"img_list3\",".$i.")' href='javascript:;' >".$i."</a>";
				}else{
					$test.="<a class='num' onclick='get_img_list(\"img_select3\",\"2\",\"img_list3\",".$i.")' href='javascript:;' >".$i."</a>";
				}
			}
			if($last_page==1){
				$test.="<span>...</span><a onclick='get_img_list(\"img_select3\",\"2\",\"img_list3\",".$this->params['paging']['imgsize']['page'].")' href='javascript:;' >{echo:". $this->params['paging']['imgsize']['pageCount'].";/}</a>";
			}
			$test.="<a class='nextPage' onclick='get_img_list(\"img_select3\",\"2\",\"img_list3\",".($this->params['paging']['imgsize']['page'] +1 ).")' href='javascript:;' >下一页</a>";
		}
		$str.="<div class='clear'></div><div class='pagenav clearfix' style='margin:10px 0'>".$test."</div>";
		echo $str;

		exit;
	}	

	public function getattributelist() {	
        $v = intval($_POST['v']);	
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));		

		$query = array(
				'fields' => array('attribute.*'),
				'conditions' => array('attribute.cat_id' => $v),
				'order' => 'sort_order asc'
				);	
		$result = POP::exe('[@@:UM attribute][@@:QU find:all]',$query);			
		
        if(!$result) {
	        exit("-1");
        }	
	    $array = array();
	    if($result) {
		    $i = 0;
		    foreach($result as $k=>$v) {
			    $array[$i]['attr_id'] = $v['attribute']['id'];
			    $array[$i]['attr_name'] = iconv('GB2312','UTF-8' , $v['attribute']['attr_name']);
			    $array[$i]['input_type'] = $v['attribute']['input_type'];
			    $array[$i]['attr_values'] = iconv('GB2312','UTF-8' , $v['attribute']['attr_values']);
			    $i++;
		    }
	    }
        echo json_encode($array);
		exit;
	}	
	
	
	public function getcatbrandlist() {	
        $cat_id = intval($_POST['cat_id']);
        if(!$cat_id) {
	        exit();
        }		
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));		

		$query = array(
				'fields' => array('brandgoodscategories.*'),
				'conditions' => array('brandgoodscategories.category_id' => $cat_id),
				);	
		$brand_ids = POP::exe('[@@:UM brandgoodscategories][@@:QU find:all]',$query);	

		
	    $arr = array();
	    foreach ($brand_ids as $value){	
			$query = array(
					'fields' => array('brand.*'),
					'conditions' => array('brand.id' => $value['brandgoodscategories']['brand_id']),
					);	
			$temp = POP::exe('[@@:UM brand][@@:QU find:first]',$query);			
			
			
		    $temp1 = array();		
		    $temp1['id']=$temp['brand']['id'];
		    $temp1['brand_name']=iconv('GB2312','UTF-8' , $temp['brand']['brand_name']);
		    $arr[]=$temp1;		
	    }
	    echo json_encode($arr);	
		exit;
	}			
	
	function getnbsp($i) {
		$str = '';
		if($i) {
			for($j=0; $j<$i; $j++) {
				$str .= "　";
			}
		}
		return $str;
	}	

	public function swfupload() {
	
		$upload_name = "Filedata";
		$uploadErrors = array(
			0=>"文件上传成功",
			1=>"上传的文件超过了 php.ini 文件中的 upload_max_filesize directive 里的设置",
			2=>"上传的文件超过了 HTML form 文件中的 MAX_FILE_SIZE directive 里的设置",
			3=>"上传的文件仅为部分文件",
			4=>"没有文件上传",
			6=>"缺少临时文件夹"
		);    
		if (!isset($_FILES[$upload_name])) {
			echo ("没有发现文件 ");
			exit(0);
		} else if (isset($_FILES[$upload_name]["error"][0]) && $_FILES[$upload_name]["error"][0] != 0) {
			echo ($uploadErrors[$_FILES[$upload_name]["error"][0]]);
			exit(0);
		} else if (!isset($_FILES[$upload_name]['name'][0])) {
			echo ("文件无名称");
			exit(0);
		}
		
		$query = array(
				'fields' => array('shopinfo.*'),
				'conditions' => array('shopinfo.user_id' => $this->my->id),
				);	
		$shop_info = POP::exe('[@@:UM shopinfo][@@:QU find:first]',$query);			

		$row = $shop_info['shopinfo'];	

			$query = array(
					'fields' => array('userrank.*'),
					'conditions' => array('userrank.id' => $this->my->rank_id),
					);	
			$info = POP::exe('[@@:UM userrank][@@:QU find:first]',$query);					
			$privilege = unserialize($info['userrank']['privilege']);		
			if(isset($privilege[8])) {
				$Mcount = $privilege[8];
			}else {
				$Mcount = Param::read('upfiles.usersizelimit');		
			}	
		if($row['count_imgsize']>$Mcount*1024*1024){
			echo("上传图片已超过会员限定数，请清理后上传");
			exit;
		}	
		Loader::import('lib.cupload');  
		$up = new upload('jpg|gif|png|jpge',$maxsize = 1024, $field = 'Filedata');
		$up->set_dir(APP_ROOT . Param::read('upfiles.path') . '/goods/','{y}/{m}/{d}');
		$fs=$up->execute();	
		$realtxt=$fs[0];
		if($realtxt['flag']==1){
			$rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
			$rootpath = !empty($rootpath)?	('/'.$rootpath) : '';	
			$fileSrcStr= $rootpath.str_replace(APP_ROOT,"",$realtxt['dir']).$realtxt['name'];
			$post[0]['uid']=$this->my->id;
			$post[0]['img_size']=$realtxt['size'];
			$post[0]['upl_time'] = date("Y-m-d H:i:s",time());
			$post[0]['img_url'] = $fileSrcStr;
			$post[0]['is_intro_img']='1';
			if(isset($_POST["gid"])){
				$post[0]['goods_id'] = intval($_POST["gid"]);
			}	

		if(is_array($post)){
			$set = $value = $dot = '';
			foreach($post as $key=>$val){
				$row['count_imgsize']+=$val['img_size'];
				$value .= $dot."(";
				$dot = '';
				foreach($val as $k=>$v) {
					if($key==0){
						$set .= $dot."`$k`";
					}
					$value .= $dot."'$v'";
					$dot = ",";
				}
				$value .= ")";
			}
			$sql_part = "($set) values $value";
		} else {
			exit('insert_items not array');
		}
		
		$sql ="[@@:UM imgsize][@@:QU insert][_insert][_table imgsize:no] $sql_part";	
		$id= $suc =POP::exe($sql);		

		if($suc){
			$update_items['shopinfo']['count_imgsize']=$row['count_imgsize'];

			$query  = array();		
			$query['keyid'] = true;				
			$query['set'] = $update_items;	
			$query['conditions'] = array('shopinfo.id'=>$row['id']);			
			POP::exe('[@@:UM shopinfo][@@:QU save]',$query);			
			
		}
			echo $id.":".$fileSrcStr;
		}else if($realtxt[flag]==-1||$realtxt[flag]==-2){
			echo ('文件上传关闭');
		}
		exit;
	}	

	public function swfdelimage() {	
        $id=intval(Request::get_args("iid"));
        $path=Request::get_args("path");
        $update =0;

			$query = array(
					'fields' => array('imgsize.*'),
					'conditions' => array('imgsize.id' => $id,'imgsize.uid' => $this->my->id),
					);	
			$row = POP::exe('[@@:UM imgsize][@@:QU find:first]',$query);		

		if($row){
			$size = $row['imgsize']['img_size'];
			$name = $row['imgsize']['img_url'];
			

			$query = array(
					'fields' => array('goodsgallery.*'),
					'conditions' => array('goodsgallery.img_size_id' => $id),
					);	
			$rs = POP::exe('[@@:UM goodsgallery][@@:QU find:first]',$query);	
				
			//根据$t_img_size 的id查询出$t_goods_gallery表中的数据
			if($rs){
			
				//删除$t_img_size和$t_goods_gallery表中的数据
				$img_id = $rs['goodsgallery']['id'];
				$query = array('keyid'=>$img_id);			
				POP::exe('[@@:UM goodsgallery][@@:QU del]',$query);					
				//删除图片
				@unlink(rtrim(Param::read('wwwrootPatch'),'/') . str_replace($this->base,'',$rs['goodsgallery']['img_url']));
				@unlink(rtrim(Param::read('wwwrootPatch'),'/') . str_replace($this->base,'',$rs['goodsgallery']['thumb_url']));
				@unlink(rtrim(Param::read('wwwrootPatch'),'/') . str_replace($this->base,'',$rs['goodsgallery']['img_original']));
				
			}
			//然后更新将shop_info表中的总图片大小更新
			$query  = array();		
			$query['keyid'] = true;				
			$query['set']['shopinfo'] = array('count_imgsize -'=>$size);	
			$query['conditions'] = array('shopinfo.user_id'=>$this->my->id);			
			POP::exe('[@@:UM shopinfo][@@:QU save]',$query);			

			//删除$t_img_size表中的数据
			$query = array('keyid'=>$id);			
            $update = POP::exe('[@@:UM imgsize][@@:QU del]',$query);	
			
			$name = rtrim(Param::read('wwwrootPatch'),'/') . str_replace($this->base,'',$path);	 
			if($update && file_exists($name)){
				@unlink($name); 
			}
			if($update){
				echo "1";
			}else{
				echo "0";
			}
		}else{
			echo "0";
		}
		exit;		
		
		
	}	
	
	


	
    function doframe()
    {
	
     /*    header('Content-Type: text/html; charset='.Param::read('App.encoding')); */
		$this->ViewFrame('ssssssss');
		
   }
   
    function dopostajax()
    {

        header('Content-Type: text/html; charset='.Param::read('App.encoding'));
     /*    error_reporting(7);  */

		      echo "<select type=\"select\" name=\"data[sellerid]\"  ><option value=\"\" style='color:blue;'>请选择</option>";
              echo "<option value=\"\" style='color:blue;'>aaaa</option>";
		      echo "</select>";	
	    exit;
   }

    function doajax()
    {
         header('Content-Type: text/html; charset='.Param::read('App.encoding'));
      /*  error_reporting(7);  */

		      echo "<select type=\"select\" name=\"data[sellerid]\"  ><option value=\"\" style='color:blue;'>请选择</option>";

		      echo "</select>";	

exit;

/* 		$DivId = $_GET['DivId'];
		$HiddenId = $_GET['HiddenId'];



        header('Content-Type: text/html; charset='.Param::read('App.encoding'));
        error_reporting(7); 

		      echo "<select type=\"select\" name=\"data[sellerid]\"  ><option value=\"\" style='color:blue;'>请选择</option>";

			     echo " <option value=\"$DivId\">$HiddenId</option>";
		      echo "</select>";	

exit;
 */
   }






	
}

?>